<?php

/**
 * 說明 : 使用 guzzle 呼叫遠端
 * 
 *
 * 使用方法 : 
 *
 *      用cookie裡的session_id取得遠端資料
 *          use FS\Library\Http;
 *          $http = new Http();
 *          $url = '';
 *          $exec_feedbacks[] = $http->getWithCookieSessionId($url);
 *          $http = null;
 */

namespace FS\Library;

use \GuzzleHttp\Client;
use \GuzzleHttp\Cookie\CookieJar;

class Http
{

    private $client;

	// 初始化
	// ------------------------------------------------------------
	function __construct() {

        $this->client = new Client();
	}

    // 
    // ------------------------
    function __destruct( ) {

        $this->client = null;
    }

    // 用cookie裡的session_id取得遠端資料
    // ---------------------------------------------------------------------
    public function getWithCookieSessionId($url){

        // 從url取出domain
        $array_search = array( "https://", "http://" );
        $array_replace = array( "", "" );
        $domain = str_replace($array_search, $array_replace, $url);
        
        $slash_pos = strpos($domain,"/");
        if($slash_pos>0){
            $domain = substr($domain,0, $slash_pos);
        }

        // cookie
        $jar = new CookieJar();
        $cookies = [session_name() => session_id()];
        $cookieJar = $jar->fromArray($cookies, $domain);

        // 夾帶cookie呼叫遠端
        $res = $this->client->request('GET', $url, [
                'cookies' => $cookieJar
            ]);
        $body = $res->getBody();

        $jar = null;

        return($body);
    }



}

